<?php                                           
chdir(dirname(__FILE__)."/../..");
$path = getcwd();
chdir("../");
$path3 = getcwd();
chdir(dirname(__FILE__));
#debug($path3 , $path2);
include_once $path3."/lib/core.class.php";

include_once $path3."/include/classes/loosediamonds.php";

class ProductList extends IPlugin {
        var $color;

        function ProductList($parent = null) {
                IPlugin :: IPlugin($parent);
                $this->tplfolder = dirname(__FILE__)."/tpl";
                $this->color = "blue";
        }

        function getPluginTag() {
                return "productlist";
        }
        function getPluginName() {
                return "Product List Plugin";
        }
        function getPluginVersion() {
                return "1.0.0";
        }

        function getProperty($p = null) {
                if (null == $p) {
                        return array ("MenuTitle", "MenuBlockTitle");
                }
                $result = "";
                switch ($p) {
                        case "MenuBlockTitle" :
                                {
                                        return "Shopping cart";
                                }
                                break;
                        case "MenuTitle" :
                                {
                                        return "Product";
                                }
                                break;
                };
                return $result;
        }

        // ----------------------------------------------------------------------------------
        // --- [ Handling all actions ] -----------------------------------------------------
        // ----------------------------------------------------------------------------------

        function doAction($params) {
            $core = getCoreInstance();
            $db = $core->getProperty("db");
            //$render = $core->framework->smarty;
                    if (null != ($result = IPlugin :: doAction($params))) {
                            return $result;
                    }
                    $arg = getCoreInstance();
                    $arg = $arg->getGET();
            if (isset($_GET[del_id])) {$db->Exec("delete from catalog where catalog_id=$_GET[del_id]");} ;
            if (isset($_GET[del_img])) 
            {
                $db->Exec("update catalog set $_GET[del_img]=NULL where catalog_id=$_GET[id]");
            }
            # ========================================================================
            # Diamond Edit
            # ========================================================================
            if($_POST['action'] == "doEditProductDiamond"){
                #debug('do action edit or Add Diamond');
                debug($_POST , "POST in");
                $z = $_POST;
                $id = $z['id'];
                if( !empty($id)){
                    # update
                    
                }else{
                    # add 
                    debug("add");
                    $loosediamond = new LooseDiamond($db);
                    
                    # ---- is_active 
                    if( $z['is_active'] == 'on'){
                        $z['is_active']  = 'Y';
                    }
                    if( empty($z['is_active']) ){
                        $z['is_active'] = 'N';
                    }
                    # ---- is_active 
                    unset($z['action'], $z['tab']);
                    #debug($z , "POST updated");
                    $id = $loosediamond->create($z);
                    $loosediamond->finish();
                    debug($id , "new id = $id");
                    #debug($loosediamond , "loosediamond");
                }
            
                
                
                #die();
                redirect("?".$this->getURL());
            }
            # EOF 
            # ========================================================================
            if ($_GET[action]=="doSubmitFaq") 
            {
                
                $is_active=0; if (isset($_POST[active])) $is_active=1; 
                $db->Exec("update products_faq set question='".str2db($_POST[question])."', answer='".str2db($_POST[answer])."', is_active='$is_active' where catalog_id=$_GET[id] and faq_id=$_GET[faq_id]");
                $GLOBALS[result_faq]="<br>&nbsp;&nbsp;&nbsp;&#8226;&nbsp;&nbsp;<font color=\"green\">Result (faq) : item (id=\"$_GET[faq_id]\") was successfully submited</font><br>";
            } 
            if ($_GET[action]=="add_faq")  
            {
                
                $faq_id=$db->getone("select max(faq_id) from products_faq where catalog_id=$_POST[id]")+1;
                $id=$db->Exec("insert into products_faq(catalog_id,faq_id,date,user) values ($_POST[id],$faq_id,now(),1)");
                $GLOBALS[result_faq]="<br>&nbsp;&nbsp;&nbsp;&#8226;&nbsp;&nbsp;<font color=\"green\">Result (faq) : item (id=\"$faq_id\") was successfully added</font><br>";
                header("location: ?path=orderslist,productlist&page=edit&parent_id=".$db->getOne("select parent_id from catalog where catalog_id={$_POST[id]}")."&catalog_id=0&id={$_POST[id]}&tab=5");
                exit();
            }
            if ($_GET[action]=="doDeleteFaq")  
            {
                
                $db->Exec("delete from products_faq where catalog_id=$_GET[id] and faq_id=$_GET[faq_id]");
                $GLOBALS[result_faq]="<br>&nbsp;&nbsp;&nbsp;&#8226;&nbsp;&nbsp;<font color=\"green\">Result (faq) : item (id=\"$_GET[faq_id]\") was successfully removed</font><br>";
            }
            if ($_GET[action]=="doSubmitTestimonial") 
            {
                
                
                $is_active=0; if (isset($_POST[active])) $is_active=1; 
                $db->Exec("update products_testimonials set fake_state='".str2db($_POST[fake_state])."' , fake_user='".str2db($_POST[fake_name])."' , text='".str2db($_POST[text])."', is_active='$is_active' where catalog_id=$_GET[id] and testimonial_id=$_GET[testimonial_id]");
                $GLOBALS[result_testimonials]="<br>&nbsp;&nbsp;&nbsp;&#8226;&nbsp;&nbsp;<font color=\"green\">Result (testimonials) : item (id=\"$_GET[testimonial_id]\") was successfully submited</font><br>";
            }
            if ($_GET[action]=="add_testimon")  
            {
                
                $t_id=$db->getone("select max(testimonial_id) from products_testimonials where catalog_id=$_POST[id]")+1;
                $id=$db->Exec("insert into products_testimonials(catalog_id,testimonial_id,date,user) values ($_POST[id],$t_id,now(),1)");
                $GLOBALS[result_testimonials]="<br>&nbsp;&nbsp;&nbsp;&#8226;&nbsp;&nbsp;<font color=\"green\">Result (testimonials) : item (id=\"$t_id\") was successfully added</font><br>";
                header("location: ?path=orderslist,productlist&page=edit&parent_id=".$db->getOne("select parent_id from catalog where catalog_id={$_POST[id]}")."&catalog_id=0&id={$_POST[id]}&tab=6");
                exit();
            } 
            if ($_GET[action]=="doDeleteTestimonial")  
            {
                                    
                $db->Exec("delete from products_testimonials where catalog_id=$_GET[id] and testimonial_id=$_GET[testimonial_id]");
                $GLOBALS[result_testimonials]="<br>&nbsp;&nbsp;&nbsp;&#8226;&nbsp;&nbsp;<font color=\"green\">Result (testimonials) : item (id=\"$_GET[testimonial_id]\") was successfully removed</font><br>";
            } 
        
////////////////////////////////////////////////////////////  
        if ("doEditProduct" == $_POST["action"])  
                { //|| ("doEditProduct" == $_GET["action"]))
                                
                                /* attachment */
                        if(isset($_POST['attachment'])){
                                
                                $this->set_attach_child($_POST['catalog_id'],$_POST['attachment']);
                                unset($_POST['attachment']);
                        }
        
                        /* Warrantyes update/add */
                        if (isset($_POST['warrantyes']) and is_array($_POST['warrantyes'])){
                                $w = $_POST['warrantyes'];
                                unset($_POST['warrantyes']);
                                
                                        if('' == $w[0]){
                                                /* no warranties selected, deleting warranty list for item */
                                                        $db->Exec("delete from products_warranty where catalog_item_id = '".str2db($_POST['catalog_id'])."'");
                                        } 
                                        else{
                                                        $db->Exec("delete from products_warranty where catalog_item_id = '".str2db($_POST['catalog_id'])."'");
                                        
                                                foreach($w as $k => $v){    /* cheching for each value from list, is it in db or not */
                                                        if($db->getone("select warranty_id from products_warranty where warranty_type_id = '".$v."' and catalog_item_id = '".str2db($_POST['catalog_id'])."'"))
                                                        {
                                                                                        /* if value NOT in db, adding row, if value in db, doing nothing */
                                                                                }
                                                        else{
                
                                                                $db->Exec("insert into products_warranty (catalog_item_id,warranty_type_id) VALUES('".str2db($_POST['catalog_id'])."','".str2db($v)."')");      
                                                                
                                                        }
                                                }
                                        }
                        }
                        $z = $_POST;
                        
                        
                        $uid = $z["id"];
                        $catalog_id = $z['catalog_id'];
                        
                                $copy_to = "uploads/".$z['catalog_id'];
                                @ uploadFile('img_small', "/inventory/".$copy_to."_small.jpg");
                                if (isne($_FILES['img_small']['tmp_name']))
                                        $z['img_small'] = $copy_to."_small.jpg";
                                @ uploadFile('img_large', "/inventory/".$copy_to."_large.jpg");
                                if (isne($_FILES['img_large']['tmp_name']))
                                        $z['img_large'] = $copy_to."_large.jpg";
                                @ uploadFile('img_hires', "/inventory/".$copy_to."_hires.jpg");
                                if (isne($_FILES['img_hires']['tmp_name']))
                                        $z['img_hires'] = $copy_to."_hires.jpg";                
                                        
                                @ uploadFile('img_large1', "/inventory/".$copy_to."_large1.jpg");
                                if (isne($_FILES['img_large1']['tmp_name']))
                                        $z['img_large1'] = $copy_to."_large1.jpg";
                                @ uploadFile('img_hires1', "/inventory/".$copy_to."_hires1.jpg");
                                if (isne($_FILES['img_hires1']['tmp_name']))
                                        $z['img_hires1'] = $copy_to."_hires1.jpg";
                                @ uploadFile('img_large2', "/inventory/".$copy_to."_large2.jpg");
                                if (isne($_FILES['img_large2']['tmp_name']))
                                        $z['img_large2'] = $copy_to."_large2.jpg";
                                @ uploadFile('img_hires2', "/inventory/".$copy_to."_hires2.jpg");
                                if (isne($_FILES['img_hires2']['tmp_name']))
                                        $z['img_hires2'] = $copy_to."_hires2.jpg";
                                @ uploadFile('img_large3', "/inventory/".$copy_to."_large3.jpg");
                                if (isne($_FILES['img_large3']['tmp_name']))
                                        $z['img_large3'] = $copy_to."_large3.jpg";
                                @ uploadFile('img_hires3', "/inventory/".$copy_to."_hires3.jpg");
                                if (isne($_FILES['img_hires3']['tmp_name']))
                                        $z['img_hires3'] = $copy_to."_hires3.jpg";
                                
                                
                                unset ($z["action"], $z["id"], $z['catalog_id']);
                                
                                if (!in_array('is_active', array_keys($z))) {
                                        $z["is_active"] = 'N';
                                } else {
                                        if ('on' == $z['is_active']) {
                                                $z["is_active"] = 'Y';
                                        }
                                }
                                

                                if ($z['tab'] == 1) {
                                         $z['prod_details'] = array();
                        if (count($z['det_title']) != 0)
                        foreach ($z['det_title'] as $key => $det_title)
                        {
                            $z['prod_details'][] = array("title" => $det_title, "value_det" => $z['val_det'][$key]);
                        }
                        $z['prod_details'] = serialize($z['prod_details']);
                        
                            unset($z['p_title']);
                            unset($z['det_title']);
                            unset($z['val_det']);
                            unset($z['ndetails']);
                            unset($z['nprices']);
                            unset($z['ent_title']);
                            unset($z['ent_price']);
                            unset($z['ent_det_title']);
                            unset($z['ent_det_val']);
                                }
                                // get& update prices
                                $post_prices = $z['p'];
                                unset ($z['p']);unset ($z['tab']);
                        
                                if (isset($z[about])) $z[about]=str2db($z[about]);
                                if (isset($z[how_to_use])) $z[how_to_use]=str2db($z[how_to_use]);
                                
                //////////   QTY  /////////////////////// ..................
                                   if (isset($z[add]))  
                                   {
                                                if ($z[add]!="")
                                                {
                                                          if (!(is_numeric($z[add])) || strpos($z[add],".")) {$GLOBALS[result_qty]="<font color=\"red\">enter number, please ! </font>";unset ($z[qty]);}
                                                          else 
                                                          {
                                                                $GLOBALS[result_qty]="<font color=\"green\"> Complete add !</font>";
                                                                $db->Exec("insert into store_history (catalog_id,date,action,qty) values ($uid,now(),'add',$z[add])");
                                                                /// alert check
                                                                $db->exec("update catalog set min_qty_alert=0 where catalog_id=$uid");
                                                                ////////////////                            
                                                          }
                                                }
                                                unset ($z[add]);      
                                   }
                        // start our_ & list prices some filter , if not enabled, price < 0 
                        
                        if (!isset($z['price_list_on']) and $z['list_price'] > 0)
                        {
                                $z['list_price'] *= -1;
                                        
                        }
                        if (!isset($z['price_our_on']) and $z['our_price'] > 0)
                        {
                                $z['our_price'] *=  -1;
                                        
                        }
                        // end our_ & list prices some filter , if not enabled, price < 0 
        
        // ------- Products group with Begin        
                        unset($z['list_catalogs']);
                        unset($z['list_products']);
                        if (isset($z['list_selected_products']))
                        {
                                $z['group_with'] = "";
                                foreach ($z['list_selected_products'] as $product)
                                {
                                        $z['group_with'] .= $product . ",";
                                }
                        }
                        unset($z['list_selected_products']);
        // ------- Products group with End        
                
                        unset($z['price_list_on'],$z['price_our_on']);
                        $z[is_temp]='0';
        
                                $set = "";
                                foreach ($z as $k => $v) {
                                        $set .= ($set == "" ? "" : ", ")."{$k} = '".str2db($v)."'";
                                }
                                
                                $sql = "update catalog set {$set} where catalog_id='{$catalog_id}'";
                                
                                $db->Exec($sql);
        
                                if ($_SESSION[is_add]==1 )
                                { 
                                        unset($_SESSION[is_add]);
                                        header("Location: ?path=orderslist,productlist");
                                }
                                
                                
                                unset($_POST);
                                unset($_GET);
                                unset($z);
                }
////////////////////////////////////////////////////////////            
                elseif ("swap" == $_POST['action']) {
                        $chbx = $_POST['chbx'];
                        $parent_id = $_REQUEST['parent_id'];

                        $core = getCoreInstance();
                        $db = $core->getProperty("db");

                        $q = " select catalog_id,sibling from     catalog where parent_id='{$parent_id}' and catalog_id in ({$chbx[0]},{$chbx[1]})";
                        $res = $db->getAll($q);
                        $arg = array (array ($res[1][sibling], $res[0][catalog_id]), array ($res[0][sibling], $res[1][catalog_id]),);
                        $db->Exec("update     catalog set sibling=? where catalog_id=?", 0, $arg);

                }
                elseif ("insert_after" == $_POST['action']) {
                        $chbx = $_POST['chbx'];
                        $sibling_count = $_POST['sibling_count'];
                        $parent_id = $_REQUEST['catalog_id'];

                        $core = getCoreInstance();
                        $db = $core->getProperty("db");
                        $not_in == "";
                        for ($i = 0; $i < sizeof($chbx); $i ++) {
                                $not_in .= ($i == 0 ? "" : ", ")."'{$chbx[$i]}' ";
                        }
                        $q = " select catalog_id,sibling from     catalog where parent_id='{$parent_id}' and sibling> '{$sibling_count}' and catalog_id not in ({$not_in})";
                        $res = $db->getAll($q);

                        $arg = array ();
                        for ($i = 0; $i < sizeof($chbx); $i ++) {
                                $arg[$i] = array (++ $sibling_count, $chbx[$i]);
                        }
                        for ($i = 0; $i < sizeof($res); $i ++) {
                                $arg[] = array (++ $sibling_count, $res[$i]['catalog_id']);
                        }
                        $db->Exec("update     catalog set sibling=? where catalog_id=?", 0, $arg);

                }
                elseif ("insert_before" == $_POST['action']) {
                        $chbx = $_POST['chbx'];
                        $sibling_count = $_POST['sibling_count'];
                        $parent_id = $_REQUEST['catalog_id'];

                        $core = getCoreInstance();
                        $db = $core->getProperty("db");
                        $not_in == "";
                        for ($i = 0; $i < sizeof($chbx); $i ++) {
                                $not_in .= ($i == 0 ? "" : ", ")."'{$chbx[$i]}' ";
                        }
                        $q = " select catalog_id,sibling from catalog where parent_id='{$parent_id}' and sibling >= '{$sibling_count}' and catalog_id not in ({$not_in}) order by sibling";
                        $res = $db->getAll($q);

                        $arg = array ();
                        for ($i = 0; $i < sizeof($chbx); $i ++) {
                                $arg[$i] = array ($sibling_count ++, $chbx[$i]);
                        }
                        for ($i = 0; $i < sizeof($res); $i ++) {
                                $arg[] = array ($sibling_count ++, $res[$i]['catalog_id']);
                        }
                        $db->Exec("update catalog set sibling=? where catalog_id=?", 0, $arg);

                }
                elseif ("sibling_delete" == $_POST['action']) {
                        $chbx = $_POST['chbx'];
                        $sibling_count = $_POST['sibling_count'];
                        $parent_id = $_REQUEST['catalog_id'];

                        $core = getCoreInstance();
                        $db = $core->getProperty("db");
                        $not_in == "";
                        for ($i = 0; $i < sizeof($chbx); $i ++) {
                                $not_in .= ($i == 0 ? "" : ", ")."'{$chbx[$i]}' ";
                        }
                        $q = "delete from catalog where catalog_id in ({$not_in})";
                        $db->Exec($q);
                }
                elseif ("move_to_folder" == $_POST['action']) {
                        $chbx = $_POST['chbx'];
                        $sibling_count = $_POST['sibling_count'];
                        $parent_id = $_REQUEST['catalog_id'];

                        $core = getCoreInstance();
                        $db = $core->getProperty("db");
                        $in == "";
                        for ($i = 0; $i < sizeof($chbx); $i ++) {
                                $in .= ($i == 0 ? "" : ", ")."'{$chbx[$i]}' ";
                        }
                        $q = "update catalog set parent_id='{$sibling_count}' where catalog_id in ({$in})";
                        $db->Exec($q);
                }
                //doDeleteCatalog
                if ("doDeleteProduct" == $_GET['action']) {
                        $uid = $_GET['id'];
                        if (empty ($uid) || $uid < 0 || !is_numeric($uid)) {
                                header("location: ./?".$this->getURL());
                                exit ();
                        }
                        $core = getCoreInstance();
                        $db = $core->getProperty("db");

                        $sql = "delete from catalog where catalog_id=".str2db($uid)."";
                        $db->Exec($sql);
                }
        }

        // ----------------------------------------------------------------------------------
        // --- [ Render pages ] -------------------------------------------------------------
        // ----------------------------------------------------------------------------------

        function Render($params) {
                global $_G;
                if (null != ($result = IPlugin :: Render($params))) {
                        return $result;
                }

                $core = getCoreInstance();
                $render = $core->framework->smarty;
                $render->assign("baseurl", "?".$this->getURL()."&page=".$_G["page"]);

                $page = "";

                switch ($_G["page"]) {

                    case "checkvalid" :
                        $page = $this->renderCheck($render);
                        break;

                    case "edit" :
                        $page = $this->renderProductEdit($render);
                        break;

                    case "edit_about" :
                        $page = $this->renderProductEdit_about($render);
                        break;
                    case "edit_howto" :
                        $page = $this->renderProductEdit_howto($render);
                        break;

                    case "add" :
                            $page = $this->renderProductAdd($render);
                            break;
                    case "add_diamond" :
                            $page = $this->renderProductAddDiamond($render);
                            break;
                    case "store_history" :
                        $page = $this->renderStoreHistory($render);
                        break;                
                    default :
                        $page = $this->renderProductList($render);
                        break;
                }

                return $render->fetch("file:".$this->tplfolder."/".$page);
        }

        // ----------------------------------------------------------------------------------
        // --- [ Generate CProduct List ] --------------------------------------------------
        // ----------------------------------------------------------------------------------

        function cb_renderCT($data) {
                $catalog_id = $_REQUEST['catalog_id'];

                if (isne($catalog_id)) {
                        if ($catalog_id < 0 || !is_numeric($catalog_id)) {
//                              header("location: ./?".$this->getURL());
//                              exit ();
                        }
                } else {
                        $catalog_id = 0;
                }
                $parent_id = "";

                if (isne($_REQUEST['parent_id']))
                        $parent_id = $_REQUEST['parent_id'];

                $st_paginator_page = $_REQUEST['st_paginator_page'];
                $st_paginator_ppv = $_REQUEST['st_paginator_ppv'];

                $img_small = $data["img_small"];
                $core = & getCoreInstance();
        if (file_exists($core->config["file_root"]."/inventory/".$img_small) && is_file($core->config["file_root"]."/inventory/".$img_small)) {
                $img_small = "<img src='".$core->config["http_root"]."/inventory/{$img_small}' border=0 height=80/>";
        } else {
                        $img_small = "No Image";
                }

                //phpinfo();    

                $dt = array (array ("<input style='border:none;' type='checkbox' name='chbx[]' value='{$data["catalog_id"]}' />", "align='center' "), array ($data["catalog_id"], "align=\"center\""), array ($data["sibling"], "align=\"center\""), array ($img_small, ""), array ($data["title"], ""), array ('Y' == $data["is_active"] ? "Yes" : "No", "align='center'"), array ("<a href=\"?".$this->getURL()."&page=edit&parent_id={$parent_id}&catalog_id={$catalog_id}&id={$data[catalog_id]}&st_paginator_page=".$st_paginator_page."&st_paginator_ppv=".$st_paginator_ppv."\">edit</a>&nbsp;<a href=\"?".$this->getURL()."&action=doDeleteProduct&parent_id={$parent_id}&catalog_id={$catalog_id}&id={$data[catalog_id]}&st_paginator_page=".$st_paginator_page."&st_paginator_ppv=".$st_paginator_ppv."\">delete</a>", "align=\"center\""));
                return $dt;
        }






        function renderProductList(& $render) {
                $core = & getCoreInstance();
                $db = $core->getProperty("db");

                $hs = & $core->getSnippet("historylinks");
                
                if (isne($_POST[id])) {
                        $curent_catalog_id = $_POST[id];
                }
                
                if (isne($_GET['parent_id'])) {
                        $curent_catalog_id = $_GET['parent_id'];

                }
                elseif (isne($_POST['parent_id'])) {
                        $curent_catalog_id = $_POST['parent_id'];
                } else {
                        $curent_catalog_id = 0;
                }
                $sb = & $core->getSnippet("sibling");
                $sibling_params = array ("action" => "removeWrongSibling", "table" => "catalog", "sField" => "sibling", // ordering field
            "sId" => "catalog_id", "sParentId" => "parent_id", "sWhere" => "is_category != 'Y'", "sOrderBy" => " order by title",);
                $sb->doAction($sibling_params); // remove sibling = -1

                // ===== end of  sibling = -1*/
                        $params = array ("startfrom" => $curent_catalog_id, "f_id" => "catalog_id", "f_parent" => "parent_id", "f_title" => "title", "table" => "catalog", "stopval" => 0, // root
                "url" => "?".$this->getURL()."&catalog_id=###", // ### will be replaced by id
            "html_root" => "Root", "html_url" => "?".$this->getURL(), "html_separatop" => " :: ",);
                $HTML1 = $hs->Render($params);
                $render->assign("catalog_hs", $HTML1."<br/>");

                $pg = & $core->getSnippet("paginator");
                $tmp_url = $this->getURL()."&parent_id=".$curent_catalog_id;
                //      $tmp_url = $this->getURL()."&catalog_id=".$_REQUEST['catalog_id'];
                $page = $ppg = -1; /// curent count page
                        $params = array ("cb_class" => & $this, "cb_func" => cb_renderCT, "urlbase" => $tmp_url, "caption" => "Products list", "emptymsg" => "No products collected yet", "header" => array ("Check", "ID", "Sibling", "IMG", "Title", "Active", "Action"), "items" => "", "source" => "sql", // -- sql, array
                "sql_items" => "select catalog_id, title,is_active,img_small,sibling from catalog where is_category != 'Y' and parent_id='".$curent_catalog_id."' order by sibling", "sql_count" => "select count(*) from catalog where is_category != 'Y' and parent_id='".$curent_catalog_id."'", "ippg" => 15, // -- items per page
                "nppv" => 5, // -- number pages per view
               "page" => & $page, "ppg" => & $ppg,);
                $HTML = $pg->Render($params);
                $render->assign("productlist", $HTML);

                getAllHistory(null, "", $res);
                $render->assign("folder_locations", $res);

                $st_paginator_page = $_REQUEST['st_paginator_page'];
                $st_paginator_ppv = $_REQUEST['st_paginator_ppv'];

                $render->assign("add_url", "?".$this->getURL()."&parent_id=".$curent_catalog_id."&page=add&st_paginator_page=".$st_paginator_page."&st_paginator_ppv=".$st_paginator_ppv);
                $render->assign("add_url_diamond", "?".$this->getURL()."&parent_id=".$curent_catalog_id."&page=add_diamond&st_paginator_page=".$st_paginator_page."&st_paginator_ppv=".$st_paginator_ppv);
                $render->assign("url_location", "?".$this->getURL());
                $render->assign("cur_catalog", $curent_catalog_id);

                //       Sibling
                $render->assign("folder_locations", $res);

                $res_folder_str = "";
                for ($i = 0; $i < sizeof($res); $i ++) {
                        $res_folder_str .= join("|", $res[$i]);
                        if ($i != sizeof($res) - 1) {
                                $res_folder_str .= "||";
                        }
                }
                $res_folder_str = "0".$res_folder_str; /// root without id

                $sql_action = "select catalog_id,sibling, title from catalog where is_category != 'Y' and parent_id='".$curent_catalog_id."' order by sibling limit ". ($page * 10).", 10";
                $res_action = $db->getAll($sql_action);
                $res_action_str = "";
                for ($i = 0; $i < sizeof($res_action); $i ++) {
                        $res_action_str .= join("|", $res_action[$i]);
                        if ($i != sizeof($res_action) - 1) {
                                $res_action_str .= "||";
                        }
                }

                $render->assign('action_url', "?".$this->getURL()."&parent_id=".$curent_catalog_id);
                $params = array ("action_url" => "?".$this->getURL(), "action_list" => array ("swap", "insert_after", "insert_before", "sibling_delete", "move_to_folder"), "insert_list_str" => $res_action_str, "res_folder_str" => $res_folder_str,);
                $SB_HTML = $sb->Render($params);

                $render->assign('sibling', $SB_HTML);
                

                $render->assign("check_valid", "?".$this->getURL()."&page=checkvalid");

                
                return "productlist.tpl.php";

        } /// renderProductList



// ----------------------------------------------------------------------------------
// --- [ Generate Product Edit page ] --------------------------------------------------
// ----------------------------------------------------------------------------------



        function renderProductEdit(& $render) {
         
                $core = & getCoreInstance();
                $db = $core->getProperty("db");

//---------------Metals Start-----------------------------------------
        $all_metals = $db->getAll("select * from metal");
        $render->assign("metal", $all_metals);
//---------------Metals end-----------------------------------------

        if (isset($_GET[id])) $uid=$_GET[id]; 
        if (isset($_POST[id]) && $_POST[id]!="") $uid=$_POST[id];
        
        /*if (empty ($uid) || $uid < 0 || !is_numeric($uid)) {
                        header("location: ./?".$this->getURL());
                        exit ();
                }*/
        $tab=1;
        if (isset($_GET[tab])) $tab=$_GET[tab]; 
        if (isset($_POST[tab])) $tab=$_POST[tab];
        $render->assign("tab", $tab);
                $catalog_id = $_REQUEST['catalog_id'];
                if (isne($catalog_id)) {
                        if ($catalog_id < 0 || !is_numeric($catalog_id)) {
                                header("location: ./?".$this->getURL());
                                exit ();
                        }
                } else {
                        $catalog_id = 0;
                }
                $parent_id = "";
                if (isne($_REQUEST['parent_id']))
                        $parent_id = $_REQUEST['parent_id'];
                $render->assign("parent_id", $parent_id);

                $st_paginator_page = $_REQUEST['st_paginator_page'];
                $st_paginator_ppv = $_REQUEST['st_paginator_ppv'];

                $hs = & $core->getSnippet("historylinks");
                  $params = array ("startfrom" => $parent_id, "f_id" => "catalog_id", "f_parent" => "parent_id", "f_title" => "title", "table" => "catalog", "stopval" => 0, // root
               "url" => "?path=orderslist,cataloglist&catalog_id=###", "html_root" => "Root", "html_url" => "?".$this->getURL(), "html_separatop" => " -> ",);
                $hs_edit = $hs->Render($params);

                //$render->assign("url", "?".$this->getURL()."&page=edit&parent_id=".$parent_id."&st_paginator_page=".$st_paginator_page."&st_paginator_ppv=".$st_paginator_ppv);
                $render->assign("url", "?".$this->getURL());
                $render->assign("cancel_url", "?".$this->getURL()."&parent_id=".$parent_id."&st_paginator_page=".$st_paginator_page."&st_paginator_ppv=".$st_paginator_ppv);
                $render->assign("id", $uid);
                $render->assign("parent_string", $parent_id);
        $render->assign("catalog_hs", $hs_edit);
        $render->assign("action", 'doEditProduct');
                $render->assign("title", 'Edit Product');
                $item = ArrayDb2Str($db->getRow("select * from catalog where catalog_id={$uid}"));

                // -------------------------------
                $sBasePath = "../lib/fckeditor/";
                $oFCKeditor = new FCKeditor('about');
                $oFCKeditor->BasePath = $sBasePath;
                $oFCKeditor->ToolbarSet = "Basic"; // Optimum//Default
                $oFCKeditor->Width = 650;
                $oFCKeditor->Height = 399;
                $oFCKeditor->Value = str_replace(array ("<!--", "-->"), "", db2str($item["about"]));
                $render->assign("fck_editor_about", $oFCKeditor->CreateHtml());
        // -------------------------------
        $sBasePath = "../lib/fckeditor/";
        $oFCKeditor = new FCKeditor('how_to_use');
        $oFCKeditor->BasePath = $sBasePath;
        $oFCKeditor->ToolbarSet = "Basic"; // Optimum//Default
        $oFCKeditor->Width = 650;
        $oFCKeditor->Height = 399;
        $oFCKeditor->Value = str_replace(array ("<!--", "-->"), "", db2str($item["how_to_use"]));
        $render->assign("fck_editor_how_to_use", $oFCKeditor->CreateHtml());
        
        $item['prod_details'] = unserialize($item['prod_details']);
        $item['prod_details'] = ArrayStr2Db($item['prod_details']);
                // ----------------- F A Q ---------------------------------
        $pg = & $core->getSnippet("paginator");
        $tmp_url = $this->getURL()."&page=edit&tab=5&id=$uid&parent_id=".$curent_catalog_id;
        $page = $ppg = -1; /// curent count page
            $params = array ("cb_class" => & $this, "cb_func" => pg_faq, "urlbase" => $tmp_url, "caption" => "F A Q ", "emptymsg" => "No FAQs collected yet", "header" => array ("id", "User", "Question", "Answer", "Date &nbsp;&nbsp;<img src=\"img/asc.gif\">", "Active", "Action"), "items" => "", "source" => "sql", // -- sql, array
        "sql_items" => "select catalog_id, faq_id, question, answer,user, date, is_active from products_faq where catalog_id={$uid} order by date desc", "sql_count" => "select count(*) from products_faq where catalog_id={$uid}", "ippg" => 8, // -- items per page
        "nppv" => 5, // -- number pages per view
           "page" => & $page, "ppg" => & $ppg,);
        $HTML = $pg->Render($params);
        $render->assign("faq_list", $HTML);
        //-----------------------------------------------
        if (isset($GLOBALS[result_faq]))
        {
            $render->assign("result_faq", $GLOBALS[result_faq]);
            unset($GLOBALS[result_faq]);
        }
        
        /*$sb = & $core->getSnippet("sibling");
        $sibling_params = array ("action" => "removeWrongSibling", "table" => "products_testimonials", "sField" => "testimonial_id", // ordering field
        "sId" => "testimonial_id", "sParentId" => "catalog_id", "sWhere" => "catalog_id = {$uid}", "sOrderBy" => " order by date desc",);
        $sb->doAction($sibling_params); // remove sibling = -1*/
        /////////////////////////////////////////////////////////////
        
        // --------- T  e s t i m o n i a l s ----------------------
        
                $pg = & $core->getSnippet("paginator");
        $tmp_url = $this->getURL()."&page=edit&tab=6&id=$uid&parent_id=".$curent_catalog_id;
        $page = $ppg = -1; /// curent count page
            $params = array ("cb_class" => & $this, "cb_func" => pg_testimonials, "urlbase" => $tmp_url, "caption" => "Testimonials list", "emptymsg" => "No testimonials collected yet", "header" => array ("id","Text", "User" , "Fake User", "Fake state" , "Date &nbsp;&nbsp;<img src=\"img/asc.gif\">", "Active", "Action"), "items" => "", "source" => "sql", // -- sql, array
                "sql_items" => "select catalog_id,fake_user, user ,fake_state, fake_state , testimonial_id, text, date, is_active from products_testimonials where catalog_id={$uid} order by date desc", "sql_count" => "select count(*) from products_testimonials where catalog_id={$uid}", "ippg" => 10, // -- items per page
                "nppv" => 5, // -- number pages per view
                "page" => & $page, "ppg" => & $ppg,);
        $HTML = $pg->Render($params);
        $render->assign("testimonials_list", $HTML);
        //-----------------------------------------------
        if (isset($GLOBALS[result_testimonials]))
        {
            $render->assign("result_testimonials", $GLOBALS[result_testimonials]);
            unset($GLOBALS[result_testimonials]);
        }
        /////////////////////////////////////////////////////////////
        
        $render->assign("item", $item);
      // ---------------- Q T Y  ----------- ....  
        if (isset($GLOBALS[result_qty]))
        {
            $render->assign("result_qty", $GLOBALS[result_qty]);
            unset($GLOBALS[result_qty]);
        }
        $render->assign("qty", $db->getone("select sum(qty) from store_history where catalog_id=$uid")); 
        
//---------------Product gouping Begin-----------------------------------------
        // -- Select all catalogs
        $sql = "select title, catalog_id from catalog where is_category = 'Y' and is_active = 'Y'";
        $arr_catalogs = ArrayDb2Str($db->getAll($sql));
        $render->assign("arr_catalogs", $arr_catalogs);

        // -- Select all products in root
        $sql = "select title, catalog_id from catalog where is_category <> 'Y' and parent_id = 0 and is_active = 'Y'";
        $arr_products_root = ArrayDb2Str($db->getAll($sql));
        $render->assign("arr_products_root", $arr_products_root);


        //--- Select all selected products        
        $sql = "select group_with from catalog where catalog_id = {$uid}";
        $str_group_with = $db->getOne($sql);
        
        $arr_selected_products = array();
        if ("" != $str_group_with)
        {
             $sql = "select catalog_id, item_number, title, is_category from catalog where catalog_id in ({$str_group_with}0) order by title asc";
             $arr_selected_products = ArrayDb2Str($db->getAll($sql));
        }
        $render->assign("arr_selected_products", $arr_selected_products);
//---------------Product gouping End-----------------------------------------



//---------------Product warrantyes start-----------------------------------------

    $all_products_warranties = array();
    
    if ($this->is_child($uid)){
        //nothing
    }
    else{

        $sql  = "select * from products_warranty_types where is_active = 'Y'";
        $warantyes = Arraydb2str($db->getall($sql));

            $render->assign("warantyes", $warantyes);
    
        $sql = "select * from products_warranty";
        $all_products_warranties = $db->getall($sql);
    
        
    } //end else , if is a child, then no warranty can be ;)

        if(empty($all_products_warranties)){
                $all_products_warranties = '';
        }

        $render->assign("all_pw", $all_products_warranties);




//---------------Product warrantyes End-----------------------------------------




//---------------Product attachment start-----------------------------------------
$catalog = $this->get_items($uid);
$render->assign("attch_catalog", $catalog);
$attach = $this->get_attach_child($uid);
$render->assign("attch", $attach);

//---------------Product attachment end-----------------------------------------
        $defaultvendorid = $db->getone("select owned_by_vendor from catalog where catalog_id = '".str2db($item['parent_id'])."' and is_category = 'Y'");
        if ($defaultvendorid!="")
        $defaultvendorname = $db->getone("select vendor_name from vendors where vendor_id=$defaultvendorid");   
        $render->assign("def_vendor_id", $defaultvendorid);
        $render->assign("def_vendor_name", $defaultvendorname);
        $sql = "select * from vendors where vendor_id != '$defaultvendorid' and vendor_active = 'Y'";
        $vendors = $db->getall($sql);
        if(count($vendors) > 0){
                $render->assign("vendors", $vendors);
        }
                return "productedit.tpl.php";
        } // renderProductEdit
    

// ----------------------------------------------------------------------------------
// --- [   ] --------------------------------------------------
// ----------------------------------------------------------------------------------

    function pg_faq($data) {
        
        $st_paginator_page = $_REQUEST['st_paginator_page'];
        $st_paginator_ppv = $_REQUEST['st_paginator_ppv'];
        $catalog_id=$data[catalog_id];
        $faq_id=$data[faq_id];
        //if ($data["user"]==0) $data["user"]="Admin"; else
        $core = & getCoreInstance();
        $db = $core->getProperty("db");
        $data["user"]=$db->getone("select client_name from clients where client_id=$data[user]");
            $dt = array (
                array ("<form name=\"form".$data["faq_id"]."\" action=\"?path=orderslist,productlist&action=doSubmitFaq&page=edit&tab=5&id={$catalog_id}&faq_id=$faq_id&st_paginator_page=".$st_paginator_page."&st_paginator_ppv=".$st_paginator_ppv."\" method=\"POST\" >".$data["faq_id"], "align='center' "),
                array ($data["user"], "align='center' "),
                array ("<textarea name=\"question\" wrap=\"virtual\" class=\"input_text\" style=\"height:53px;width:185px;\">".$data["question"]."</textarea>", ""),
                array ("<textarea name=\"answer\" wrap=\"virtual\" class=\"input_text\" style=\"height:53px;width:185px;\">".$data["answer"]."</textarea>", ""),
                array ($data["date"], "align='center' "),
                array ("<input style='border:none;' type='checkbox' name='active' ".($data["is_active"]==1 ? "checked" : "")." /> </form>", "align='center' "),
                array ("<a style=\"cursor:hand\" title=\"click for submit this line\" onclick=\"document.forms['form".$data["faq_id"]."'].submit();\">apply</a>&nbsp;<a href=\"?".$this->getURL()."&action=doDeleteFaq&page=edit&tab=5&id={$catalog_id}&faq_id=$faq_id&st_paginator_page=".$st_paginator_page."&st_paginator_ppv=".$st_paginator_ppv."\" title=\"click for delete this line\">delete</a>", "align=\"center\"")  
                
                        );
            return $dt;
    }

    function pg_testimonials($data) {
        
        $st_paginator_page = $_REQUEST['st_paginator_page'];
        $st_paginator_ppv = $_REQUEST['st_paginator_ppv'];
        $catalog_id=$data[catalog_id];
        $testimonial_id=$data[testimonial_id];
        
        $core = & getCoreInstance();
        $db = $core->getProperty("db");
        //if ($data["user"]==0) $data["user"]="Admin"; else 

        $data["user"]=$db->getone("select client_name from clients where client_id=$data[user]");
    //    $fake['user']=$db->getone("select name from products_testemonials where ");
            $dt = array (
                array ("<form name=\"form_".$data["testimonial_id"]."\" action=\"?path=orderslist,productlist&action=doSubmitTestimonial&page=edit&tab=6&id={$catalog_id}&testimonial_id=$testimonial_id&st_paginator_page=".$st_paginator_page."&st_paginator_ppv=".$st_paginator_ppv."\" method=\"POST\" >".$data["testimonial_id"], "align='center' "),
                array ("<textarea name=\"text\" wrap=\"virtual\" class=\"input_text\" style=\"height:41px;width:366px;\">".db2str($data["text"])."</textarea>", ""),
                array ($data["user"], "align='center' "),
                array ("<input type='text' name='fake_name' value='".$data['fake_user']."'"),
                array ("<input type='text' name='fake_state' value='".$data['fake_state']."'"),
                array ($data["date"], "align='center' "),
                array ("<input style='border:none;' type='checkbox' name='active' ".($data["is_active"]==1 ? "checked" : "")." /> </form>", "align='center' "),
                array ("<a style=\"cursor:hand\" title=\"click for submit this line\" onclick=\"document.forms['form_".$data["testimonial_id"]."'].submit();\">apply</a>&nbsp;<a href=\"?".$this->getURL()."&action=doDeleteTestimonial&page=edit&tab=6&id={$catalog_id}&testimonial_id=$testimonial_id&st_paginator_page=".$st_paginator_page."&st_paginator_ppv=".$st_paginator_ppv."\" title=\"click for delete this line\">delete</a>", "align=\"center\"")  
                        );
            return $dt;
    }
    
// ----------------------------------------------------------------------------------
// --- [ Render Check ] --------------------------------------------------
// ----------------------------------------------------------------------------------


        function renderCheck(& $render) {

                $render->assign("check_valid", "?".$this->getURL()."&page=checkvalid");

                return "check.tpl.php";

        }
    
// ----------------------------------------------------------------------------------
// --- [ Generate Product Add Diamond Page ] --------------------------------------------------
// ----------------------------------------------------------------------------------


        function renderProductAddDiamond(& $render) {
            $core = getCoreInstance();
            $db = $core->getProperty("db");
            $render->assign("tab", 1);       
            $render->assign("title", 'Add Diamond'."<br/>");
            $render->assign("url", "?".$this->getURL()."&page=edit&parent_id=".$parent_id."&st_paginator_page=".$st_paginator_page."&st_paginator_ppv=".$st_paginator_ppv);
            $render->assign("action", 'doEditProductDiamond');
            
            # start collect Diamond selects from DB
            // 1 Shape 
            $shapes = $db->getAll("select var_id,var_key from d_select_vars where select_id=1");
            $render->assign("shapes" , $shapes);
            # 7 girdle 
            $girdle = $db->getAll("select var_id,var_key from d_select_vars where select_id=7");
            $render->assign("girdle" , $girdle);
            # 8 culet 
            $culet = $db->getAll("select var_id,var_key from d_select_vars where select_id=8");
            $render->assign("culet" , $culet);
            # 9 polish 
            $polish = $db->getAll("select var_id,var_key from d_select_vars where select_id=9");
            $render->assign("polish" , $polish);
            # 10 symmetry 
            $symmetry = $db->getAll("select var_id,var_key from d_select_vars where select_id=10");
            $render->assign("symmetry" , $symmetry);
            # 11 fluorescence 
            $fluorescence = $db->getAll("select var_id,var_key from d_select_vars where select_id=11");
            $render->assign("fluorescence" , $fluorescence);
            debug($fluorescence , "fluorescence");
            
            
         
 

    //---------------Vendors start-----------------------------------------
    
            $defaultvendorid = $db->getone("select owned_by_vendor from catalog where catalog_id = '".str2db($item['parent_id'])."' and is_category = 'Y'");
            if ($defaultvendorid!="")
            $defaultvendorname = $db->getone("select vendor_name from vendors where vendor_id=$defaultvendorid");   
            $render->assign("def_vendor_id", $defaultvendorid);
            $render->assign("def_vendor_name", $defaultvendorname);
            $sql = "select * from vendors where vendor_id != '$defaultvendorid' and vendor_active = 'Y'";
            $vendors = $db->getall($sql);
            if(count($vendors) > 0){
                    $render->assign("vendors", $vendors);
            }
    //---------------Vendors end-----------------------------------------
        
                return "product.diamond.edit.tpl.php";
        } // renderCatalogAdd
        
// ----------------------------------------------------------------------------------
// --- [ Generate Product Add Page ] --------------------------------------------------
// ----------------------------------------------------------------------------------


        function renderProductAdd(& $render) {
        $core = getCoreInstance();
        $db = $core->getProperty("db");
         
        $parent_id=$_REQUEST[parent_id];
                
        $st_paginator_page = $_REQUEST['st_paginator_page'];
        $st_paginator_ppv = $_REQUEST['st_paginator_ppv'];
         
         
        $render->assign("tab", 1);       
        $render->assign("title", 'Add Product'."<br/>");

//---------------Metals Start-----------------------------------------
        $all_metals = $db->getAll("select * from metal");
        $render->assign("metal", $all_metals);
//---------------Metals end-----------------------------------------

        $sibling=1+$db->getone("select max(sibling) from catalog");
        $db->Exec("insert into catalog(parent_id,sibling, date) values('$parent_id','$sibling','".date("Y-m-d H:i:s")."')");
        $_SESSION[del_tmp]=1;
        
        $id=mysql_insert_id();
        $db->Exec("insert into store_history (catalog_id,date,action,qty) values ($id,now(),'create',0)");
        $render->assign("qty", 0);
        $render->assign("id", $id);
        $_SESSION[is_add]=1;
        $render->assign("parent_id", $parent_id);
        $item = ArrayDb2Str($db->getRow("select * from catalog where catalog_id={$id}"));
        $render->assign("item", $item);
        $hs = & $core->getSnippet("historylinks");
         $params = array ("startfrom" => $parent_id, "f_id" => "catalog_id", "f_parent" => "parent_id", "f_title" => "title", "table" => "catalog", "stopval" => 0, // root
          "url" => "?path=orderslist,cataloglist&catalog_id=###", "html_root" => "Root", "html_url" => "?".$this->getURL(), "html_separatop" => " -> ",);
            $hs_edit = $hs->Render($params);
             $render->assign("catalog_hs", $hs_edit);
             
             
        // -------------------------------
        $sBasePath = "../lib/fckeditor/";
        $oFCKeditor = new FCKeditor('about');
        $oFCKeditor->BasePath = $sBasePath;
        $oFCKeditor->ToolbarSet = "Default"; // Optimum//Default
        $oFCKeditor->Width = 650;
        $oFCKeditor->Height = 399;
        $oFCKeditor->Value = db2str($item["about"]);
        $render->assign("fck_editor_about", $oFCKeditor->CreateHtml());
        // -------------------------------
        $sBasePath = "../lib/fckeditor/";
        $oFCKeditor2 = new FCKeditor('how_to_use');
        $oFCKeditor2->BasePath = $sBasePath;
        $oFCKeditor2->ToolbarSet = "Default"; // Optimum//Default
        $oFCKeditor2->Width = 650;
        $oFCKeditor2->Height = 399;
        $oFCKeditor2->Value = db2str($item["how_to_use"]);
        $render->assign("fck_editor_how_to_use", $oFCKeditor2->CreateHtml());
        
        $render->assign("action", 'doEditProduct');
        $render->assign("url", "?".$this->getURL()."&page=edit&parent_id=".$parent_id."&st_paginator_page=".$st_paginator_page."&st_paginator_ppv=".$st_paginator_ppv);
        $render->assign("cancel_url", "?".$this->getURL()."&parent_id=".$parent_id."&st_paginator_page=".$st_paginator_page."&st_paginator_ppv=".$st_paginator_ppv."&del_id=".$id);


//---------------Product gouping Begin-----------------------------------------
        // -- Select all catalogs
        $sql = "select title, catalog_id from catalog where is_category = 'Y' and is_active = 'Y'";
        $arr_catalogs = ArrayDb2Str($db->getAll($sql));
        $render->assign("arr_catalogs", $arr_catalogs);

        // -- Select all products in root
        $sql = "select title, catalog_id from catalog where is_category <> 'Y' and parent_id = 0 and is_active = 'Y'";
        $arr_products_root = ArrayDb2Str($db->getAll($sql));
        $render->assign("arr_products_root", $arr_products_root);
//---------------Product gouping End-----------------------------------------

//---------------Product warrantyes start-----------------------------------------

    $all_products_warranties = array();
    
    if ($this->is_child($id)){
        //nothing
    }
    else{

        $sql  = "select * from products_warranty_types where is_active = 'Y'";
        $warantyes = Arraydb2str($db->getall($sql));

            $render->assign("warantyes", $warantyes);
    
        $sql = "select * from products_warranty";
        $all_products_warranties = $db->getall($sql);
    
        
    } //end else , if is a child, then no warranty can be ;)

        if(empty($all_products_warranties)){
                $all_products_warranties = '';
        }

        $render->assign("all_pw", $all_products_warranties);




//---------------Product warrantyes End-----------------------------------------


//---------------Product attachment start-----------------------------------------
        $catalog = $this->get_items($id);
        $render->assign("attch_catalog", $catalog);
        $attach = $this->get_attach_child($id);
        $render->assign("attch", $attach);

//---------------Product attachment end-----------------------------------------


//---------------Vendors start-----------------------------------------

        $defaultvendorid = $db->getone("select owned_by_vendor from catalog where catalog_id = '".str2db($item['parent_id'])."' and is_category = 'Y'");
        if ($defaultvendorid!="")
        $defaultvendorname = $db->getone("select vendor_name from vendors where vendor_id=$defaultvendorid");   
        $render->assign("def_vendor_id", $defaultvendorid);
        $render->assign("def_vendor_name", $defaultvendorname);
        $sql = "select * from vendors where vendor_id != '$defaultvendorid' and vendor_active = 'Y'";
        $vendors = $db->getall($sql);
        if(count($vendors) > 0){
                $render->assign("vendors", $vendors);
        }
//---------------Vendors end-----------------------------------------
        
                return "productedit.tpl.php";
        } // renderCatalogAdd
    
    function renderProductEdit_about(& $render)
    {
        if (isset($_GET[id])) $uid=$_GET[id]; 
        if (isset($_POST[id])) $uid=$_POST[id];
        $render->assign("id", $uid);
        $st_paginator_page = $_REQUEST['st_paginator_page'];
        $st_paginator_ppv = $_REQUEST['st_paginator_ppv'];
        $render->assign("title", "Edit About (item id = $uid)");
        $core = & getCoreInstance();
        $db = $core->getProperty("db");
        $item = ArrayDb2Str($db->getRow("select * from catalog where catalog_id={$uid}"));
                // window.location.href = 'discounts_type.php';
        $sBasePath = "../lib/fckeditor/";
        $oFCKeditor = new FCKeditor('about');
        $oFCKeditor->BasePath = $sBasePath;
        $oFCKeditor->ToolbarSet = "Default"; // Optimum//Default
        $oFCKeditor->Width = 850;
        $oFCKeditor->Height = 499;
        $oFCKeditor->Value = db2str($item["about"]);
        $render->assign("fck_editor_about", $oFCKeditor->CreateHtml());
        $render->assign("url", "?".$this->getURL()."&page=edit&tab=3&id=$uid&st_paginator_page=".$st_paginator_page."&st_paginator_ppv=".$st_paginator_ppv);
        return "productedit_about.tpl.php";
    }
    function renderProductEdit_howto(& $render)
    {
        if (isset($_GET[id])) $uid=$_GET[id]; 
        if (isset($_POST[id])) $uid=$_POST[id];
        $render->assign("id", $uid);
        $st_paginator_page = $_REQUEST['st_paginator_page'];
        $st_paginator_ppv = $_REQUEST['st_paginator_ppv'];
        $render->assign("title", "Edit How To (item id = $uid)");
        $core = & getCoreInstance();
        $db = $core->getProperty("db");
        $item = ArrayDb2Str($db->getRow("select * from catalog where catalog_id={$uid}"));
                // window.location.href = 'discounts_type.php';
        $sBasePath = "../lib/fckeditor/";
        $oFCKeditor = new FCKeditor('how_to_use');
        $oFCKeditor->BasePath = $sBasePath;
        $oFCKeditor->ToolbarSet = "Default"; // Optimum//Default
        $oFCKeditor->Width = 850;
        $oFCKeditor->Height = 499;
        $oFCKeditor->Value =  db2str($item["how_to_use"]);
        $render->assign("fck_editor_how_to_use", $oFCKeditor->CreateHtml());
        $render->assign("url", "?".$this->getURL()."&page=edit&tab=4&id=$uid&st_paginator_page=".$st_paginator_page."&st_paginator_ppv=".$st_paginator_ppv);
        return "productedit_howto.tpl.php";
                
    }
    
    //------------------------------------------------------------------------------------------------------------------
    //--------------------< S T O R E  H I S T O R Y >------------------------------------------------------------------
    //------------------------------------------------------------------------------------------------------------------
            
    function renderStoreHistory(& $render)
    {
        if (isset($_GET[id])) $uid=$_GET[id]; 
        if (isset($_POST[id])) $uid=$_POST[id];
        $render->assign("id", $uid);
        $st_paginator_page = $_REQUEST['st_paginator_page'];
        $st_paginator_ppv = $_REQUEST['st_paginator_ppv'];
        $render->assign("title", "View store history list (item id = $uid)");
        $core = & getCoreInstance();
        $db = $core->getProperty("db");
        // Temp = 0 
        $db->exec("update catalog set is_temp=0 where catalog_id='{$uid}'");;
                // window.location.href = 'discounts_type.php';
        $operation=$db->getall("select distinct action from store_history");
        foreach ($operation as $v) {$operation_[]=$v[action];}
        $render->assign("operation", $operation_);
        $pg = & $core->getSnippet("paginator");
        $tmp_url = $this->getURL()."&page=store_history&id=$uid";
        $page = $ppg = -1; /// curent count page
        
        // -      - - - FILTER by OPERATION  - - - --- - -
        $action="all";
        $filtersql="";
        if (isset($_POST[action]) && $_POST[action]!="all") $filtersql.="and action='$_POST[action]'";
        
        $render->assign("current_filter", $_POST[action]);
        
        $params = array ("cb_class" => & $this, "cb_func" => pg_store_history, "urlbase" => $tmp_url, "caption" => "View store history list", "emptymsg" => "No items collected yet", "header" => array ( "Operation", "Quantity", "Date &nbsp;&nbsp;<img src=\"img/asc.gif\">"), "items" => "", "source" => "sql", // -- sql, array
        "sql_items" => "select action, date, qty, info from store_history where catalog_id=$uid $filtersql order by date desc", "sql_count" => "select count(*) from store_history where catalog_id=$uid $filtersql", "ippg" => 10, // -- items per page
        "nppv" => 5, // -- number pages per view
           "page" => & $page, "ppg" => & $ppg,);
        $HTML = $pg->Render($params);
        $render->assign("pg_store_history_list", $HTML);
        $render->assign("url", "?".$this->getURL()."&page=edit&tab=1&id=$uid&st_paginator_page=".$st_paginator_page."&st_paginator_ppv=".$st_paginator_ppv);
        return "productedit_store_history.tpl.php";
                
    }
    function pg_store_history($data) {
        
        $st_paginator_page = $_REQUEST['st_paginator_page'];
        $st_paginator_ppv = $_REQUEST['st_paginator_ppv'];
            $dt = array (
                array ($data["action"], "align='center' "),
                array ($data["qty"], "align='center' "),
                array ($data["date"], "align='center' width=\"120\"")
                //array ($data["info"], "align='center' ")
                        );
            return $dt;
    }

/*
                        CUSTOM FUNCTIONS , Sergey Shilko

*/

    /**
     * Will return attachment for item
     *
     * @param int $parent
     * @return array 
     */
    
    function get_attach_child($parent){
        $core = getCoreInstance();
        $db = $core->getProperty("db");
        
        if (is_numeric($parent) and $parent > 0 and '' != $parent){
                $p = str2db($parent);
                $sql = "select products_attach_item_child from products_attach where products_attach_item_parent = '$p'";
                        $child = $db->getone($sql);
                return $child;  
        }
    
        else{    
                        return ("Error: parent not numeric , or < 0, or == '' ");               
        }
    }
    
    /**
     * Will set child for parent
     *
     * @param int $parent
     * @param int $child
     * @return int
     */
    function set_attach_child($parent,$child){
        
        if (is_numeric($parent) and $parent > 0 and $parent != ''){
                 if('' != $child){
                                $core = getCoreInstance();
                                $db = $core->getProperty("db");
                                $db->Exec("delete from products_attach where products_attach_item_parent = $parent");
                                $sql = "insert into products_attach (products_attach_item_parent,products_attach_item_child) values($parent,$child)";
                                $r = $db->Exec($sql);
                                return $r;
                                
                }
                else{
                        $core = getCoreInstance();
                        $db = $core->getProperty("db");
                        $p = str2db($parent);
                        $r = $db->Exec("delete from products_attach where products_attach_item_parent = '$p'");
                }
        }
        else{
                return ("Error: parent not numeric, or < 0, or == '', or childs not array");
        }
    }
        
    /**
     * Returns all catalog exept one item
     *
     * @param int $exeptone
     * @return array
     */
    function get_items($exeptone){
        if (is_numeric($exeptone) and $exeptone > 0 and $exeptone != ''){
                $core = getCoreInstance();
                $db = $core->getProperty("db");
                $e = str2db($exeptone);
                $r = ArrayDb2str($db->getall("select catalog_id,parent_id,title from catalog where catalog_id not like '$e' and is_category not like 'Y' order by parent_id asc"));
                return $r;
        }
        else{
                return ("func get_items error");
        }
    }

    
     function is_child($someid){
        if(is_numeric($someid) and $someid > 0){
            $core = getCoreInstance();
        $db = $core->getProperty("db");
                $r = $db->getone("select count(products_attach_id) from products_attach where products_attach_item_child = {$someid}");
                if($r > 0){
                return true;
                }
                else{
                return false;
                }       
        } // end if
        else{
                return 'Error';
        } //end else-error
    }

};
?>